<?php

namespace App\Providers;

use App\Article;
use App\Image;
use App\Movie;
use App\Quote;
use App\Show;
use App\Tag;
use Carbon\Carbon;
use DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\ServiceProvider;

class ViewComposerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->composeLatestShow();
        $this->composeTagsPartial();
        $this->composeLatestMovies();
        $this->composeRecentNews();
        $this->topReviewShows();
        $this->topHotMovies();
        $this->quotesTicker();
        $this->randomImageQuote();
        $this->calendar();
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    public function composeLatestShow()
    {
        view()->composer('partials.todayShowTopCarousel', function ($view) {
            $key = 'todayShowTopCarousel';
            $shows = Cache::get($key);
            if(!$shows) {
                $shows = Show::whereDate('updated_at','=',Carbon::today()->toDateString())
                    ->orderBy('updated_at')->get();
                Cache::put($key, $shows, 1440);
            }
            $view->with('latestShows',$shows);
        });
    }

    public function composeTagsPartial()
    {
        view()->composer('partials.sidebarTags', function ($view) {
            $key = 'partials.sidebarTags';
            $tags = Cache::remember($key,3600,function (){
                return Tag::all();
            });
            $view->with('tags', $tags);
        });
    }

    public function composeLatestMovies() {
        view()->composer('partials.sidebarMovies',function($view){
            $key = 'partials.sidebarMovies';
            $latestMovies = Cache::remember($key,120,function (){
                return Movie::where('updated_at','>',Carbon::now()->subDays(30))->orderBy('updated_at','desc')->limit(45)->get();
            });
            $view->with('latestMovies',$latestMovies);
        });
    }

    public function composeRecentNews() {
        view()->composer('partials.recentNews',function($view){
            $key = 'partials.recentNews';
            $articles = Cache::remember($key,120,function (){
                return Article::orderBy('updated_at','desc')->limit(15)->get();
            });
            $view->with('articles',$articles);
        });
    }

    public function topReviewShows() {
        view()->composer('partials.topReviewShows',function($view){
            $key = 'topReviewShows';
            $shows = Cache::get($key);
            if(!$shows) {
                $shows = Show::whereHas('vote',function($q){
                    $q->where('score','>',0);
                })->take(15)->get();
                Cache::put($key,$shows, 1440);
            }
            $view->with('hotShows',$shows);
        });
    }


    public function topHotMovies() {
        view()->composer('movie._topHotMovies',function($view){
            $key = '_topHotMovies';
            $topHotMovies = Cache::get($key);
            if(!$topHotMovies) {
                $topHotMovies = Movie::whereHas('vote',function($q){
                    $q->where('score','>',3);
                })->take(15)->get();
                Cache::put($key,$topHotMovies, 1440);
            }

            $view->with('topHotMovies',$topHotMovies);
        });
    }
    public function quotesTicker() {
        view()->composer('partials.quoteTicker',function($view){
            $key = 'quote_ticker';
            $quotes = Cache::remember($key,180,function (){
                return Quote::orderBy(\DB::raw('RAND()'))->take(10)->get();
            });
            $view->with('quotes',$quotes);
        });
    }

    public function randomImageQuote() {
        view()->composer('partials.randomImageQuote',function($view){
            $key = 'view_randomImageQuote';
            $quotes = Cache::remember($key,60*2,function (){
                return Image::where('key','like', '%brainyquote%')->orderBy(\DB::raw('RAND()'))->take(3)->get();
            });
            $view->with('quotes',$quotes);
        });
    }

    public function calendar() {
        view()->composer('partials._calendar',function($view){
            $key = 'partials._calendar';
            $days = Cache::remember($key,120,function (){
                //dayofWeek 1 => sunday 7=>saturday
                $week_day_raw = Db::raw("DAYOFWEEK(episodes.created_at) AS week_day");

                $array = DB::table('episodes')->join('shows', function ($join) {
                        $a_week_ago = Carbon::now()->subDay(7);
                        $join->on('episodes.show_id', '=', 'shows.id')->where('episodes.created_at', '>=',$a_week_ago)->where('episodes.provider','like','%eztv%');
                })->select(['shows.name_en', 'shows.name_zh', 'shows.id', $week_day_raw])->distinct()->orderBy('week_day')->orderBy('shows.name_en')->get();
                $week_shows = [];
                foreach ($array as $obj){
                    //换算成php week index
                    $key = $obj->week_day-1;
                    $week_shows[$key][] = $obj;
                }
                return $week_shows;
            });
            $week_list = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];

            //php 0（表示星期天）到 6（表示星期六）
            //+1 换算成 mysql week
            $this_week_index = date('w');
//            dd($days,$this_week_index,$week_list);
            $view->with('days',$days)->with('this_week_index',$this_week_index)->with('week_list',$week_list);
        });
    }

}
